package com.zhengxyou.jetpackdemo.paging;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.zhengxyou.jetpackdemo.R;
import com.zhengxyou.jetpackdemo.room.entity.User;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;

public class PagingAdapter extends PagedListAdapter<User, PagingAdapter.PagingViewHolder> {
//    private List<User> mData = new ArrayList<>();

    public PagingAdapter() {
        super(DIFF_CALLBACK);
    }

    @NonNull
    @Override
    public PagingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_paging, parent, false);
        return new PagingViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull PagingViewHolder holder, int position) {
        holder.tv_name.setText(getItem(position).firstName);
    }

//    @Override
//    public int getItemCount() {
//        return mData.size();
//    }

//    public void setData(List<User> data) {
//        this.mData.clear();
//        this.mData.addAll(data);
//        notifyDataSetChanged();
//    }

    class PagingViewHolder extends RecyclerView.ViewHolder {
        public TextView tv_name;

        public PagingViewHolder(@NonNull View itemView) {
            super(itemView);
            tv_name = itemView.findViewById(R.id.tv_name);
        }
    }

    private static DiffUtil.ItemCallback<User> DIFF_CALLBACK = new DiffUtil.ItemCallback<User>() {
        @Override
        public boolean areItemsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            return oldItem.id == newItem.id;
        }

        @Override
        public boolean areContentsTheSame(@NonNull User oldItem, @NonNull User newItem) {
            return oldItem.equals(newItem);
        }
    };
}
